package com.spzx.product.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ProductService;
import com.spzx.product.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author spzx
 * @since 2024-12-19
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询商品列表
     *
     * @return
     */
    @Override
    public List<Product> selectProductList() {
        return baseMapper.selectProductList();
    }

    /**
     * 插入商品信息
     *
     * @param product
     * @return
     */
    @Override
    public int insertProduct(Product product) {

        //保存商品信息
        product.setCreateBy(SecurityUtils.getUsername());
        baseMapper.insert(product);

        //product:product_sku 1:n
        //存储sku信息
        List<ProductSku> productSkuList = product.getProductSkuList();

        for (int i = 0; i < productSkuList.size(); i++) {

            //product_sku:product 1:n
            ProductSku productSku = productSkuList.get(i);//获取sku信息
            productSku.setSkuCode(product.getId() + "_" + (i + 1));//设置sku编码 product_id + "_" + sku序号
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());//设置sku名称 product_name + " "+ sku规格
            productSku.setProductId(product.getId());//设置product_id
            productSku.setStatus(0);//初始值
            productSku.setCreateBy(SecurityUtils.getUsername());//设置创建人
            productSkuMapper.insert(productSku);//存储sku信息

            //product_sku:sku_stock 1:n
            //product_sku:product_sku 1:1
            SkuStock skuStock = new SkuStock();//创建sku库存对象
            skuStock.setSkuId(productSku.getId());//设置sku_id
            skuStock.setTotalNum(productSku.getStockNum());//设置总库存数量
            skuStock.setAvailableNum(productSku.getStockNum());//可用库存数量
            skuStock.setLockNum(0);//锁定库存数量
            skuStock.setSaleNum(0);//已售出数量
            skuStock.setStatus(0);//设置状态
            skuStock.setCreateBy(SecurityUtils.getUsername());//设置创建人
            skuStockMapper.insert(skuStock);//存储sku库存信息
        }
        //product:product_details   1:1
        //存商品详情信息
        ProductDetails productDetails = new ProductDetails();//创建商品详情对象
        productDetails.setProductId(product.getId());//设置product_id
        String imagesString = String.join(",", product.getDetailsImageUrlList());//将图片集合转换成字符串
        productDetails.setImageUrls(imagesString);//设置图片字符串
        productDetailsMapper.insert(productDetails);//存储商品详情信息

        return 1;
    }

    //@Transactional : rollbackFor = Exception.class : 发生异常时回滚
    //事务管理 : 保证数据的一致性
    @Transactional(rollbackFor = Exception.class)//开启事务
    @Override
    public int updateStatus(Long id, Integer status) {
        Product product = new Product();//创建商品对象
        product.setId(id);//设置商品id
        product.setStatus(status);//设置商品状态
        baseMapper.updateById(product);//更新商品状态

        //todo 1. 更新商品sku状态
        LambdaUpdateWrapper<ProductSku> updateWrapperSkuStatus =
                new LambdaUpdateWrapper<ProductSku>()
                        .eq(ProductSku::getProductId, id)
                        .set(ProductSku::getStatus, status);
        productSkuMapper.update(null, updateWrapperSkuStatus);

        //todo 2. 查询商品sku_id集合
        LambdaQueryWrapper<ProductSku> queryWrapperSkuIds =
                new LambdaQueryWrapper<ProductSku>()
                        .eq(ProductSku::getProductId, id)
                        .select(ProductSku::getId);
        List<Object> productSkuIdList = productSkuMapper.selectObjs(queryWrapperSkuIds);


        //todo 3. 更新商品sku库存状态
        LambdaUpdateWrapper<SkuStock> updateWrapperSkuStock =
                new LambdaUpdateWrapper<SkuStock>()
                        .in(SkuStock::getSkuId, productSkuIdList)
                        .set(SkuStock::getStatus, status);
        skuStockMapper.update(null, updateWrapperSkuStock);

        String key = "product:sku:data";
        if (status == 1) {
            //将 sku ID 列表放入 bitmap 中，表示上架
            productSkuIdList.forEach(productSkuId -> {
                redisTemplate.opsForValue().setBit(key, (Long) productSkuId, true);
            });
        } else {
            //将 sku ID 列表从 bitmap 中移除 ，表示下架
            productSkuIdList.forEach(productSkuId -> {
                redisTemplate.opsForValue().setBit(key, (Long) productSkuId, false);
            });
        }

        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteProductByIds(List<Long> ids) {

        //删除商品
        baseMapper.deleteBatchIds(ids);

        //先查询商品sku_id集合
        LambdaQueryWrapper<ProductSku> queryWrapper1 =
                new LambdaQueryWrapper<ProductSku>()
                        .in(ProductSku::getProductId, ids)
                        .select(ProductSku::getId);
        List<ProductSku> productSkuList = productSkuMapper.selectList(queryWrapper1);
        //获取sku_id集合
        List<Long> skuIds = productSkuList.stream().map(ProductSku::getId).collect(Collectors.toList());

        //todo 1. 再删除商品sku库存信息
        LambdaQueryWrapper<ProductSku> queryWrapper2 =
                new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids);
        productSkuMapper.delete(queryWrapper2);

        //todo 2. 删除商品sku详情信息
        LambdaQueryWrapper<ProductDetails> queryWrapper3 =
                new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, ids);
        productDetailsMapper.delete(queryWrapper3);

        //todo 3. 删除商品sku库存信息
        LambdaQueryWrapper<ProductSku> queryWrapper4 =
                new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, skuIds);

        return productSkuMapper.delete(queryWrapper4);

    }

    @Override
    public ProductVo getProductVoById(Long productId) {
        LambdaQueryWrapper<Product> queryWrapper =
                new LambdaQueryWrapper<Product>()
                        .eq(Product::getId, productId);
        Product product = baseMapper.selectOne(queryWrapper);
        ProductVo productVo = new ProductVo();
        BeanUtils.copyBeanProp(productVo, product);
        return productVo;
    }

}
